package org.devocean.groupbuying.web.frontend;

import java.security.Principal;
import java.util.Calendar;

import org.devocean.groupbuying.domain.Comment;
import org.devocean.groupbuying.service.ArticlesService;
import org.devocean.groupbuying.service.CommentService;
import org.devocean.groupbuying.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping(value = "/customers/comments")
public class CommentController {

	@Autowired
	private CommentService commentService;

	@Autowired
	private CustomerService customerService;

	@Autowired
	private ArticlesService articlesService;

	@RequestMapping(value = "/postComment")
	public String postComment(ModelMap map, Integer articleID, String text,
			Principal principal) {
		Comment comment = new Comment();
		comment.setArticle(articlesService.getArticleById(articleID));
		comment.setCustomer(customerService.getCustomerById(Integer
				.parseInt(principal.getName())));
		comment.setText(text);
		comment.setCommentDate(Calendar.getInstance().getTime());
		commentService.addOrUpdateComment(comment);
		return "deals";
	}

	@RequestMapping(value = "/reply")
	public String reply(ModelMap map, Integer commentID, String text,
			Principal principal) {
		Comment reply = new Comment();
		Comment comment = commentService.getCommentById(commentID);
		reply.setArticle(comment.getArticle());
		reply.setComment(comment);
		reply.setCustomer(customerService.getCustomerById(Integer
				.parseInt(principal.getName())));
		reply.setText(text);
		reply.setCommentDate(Calendar.getInstance().getTime());
		comment.add(reply);
		commentService.addOrUpdateComment(comment);
		return "comment";
	}

}
